import json
import sys
import requests
import os
import smtplib
import ast
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.utils import parseaddr, formataddr


'''
邮箱
'''


class EM:

    def __init__(self):
        """
        初始化
        """
        self.msg_from = '545-rujia@163.com'  # 发送方邮箱 545-rujia@163.com
        self.passwd = 'MRUphZ5NpngmYyim'  # 填入发送方邮箱的授权码
        self.s = smtplib.SMTP_SSL("smtp.163.com", 465)  # 邮件服务器及端口号
        self.s.login(self.msg_from, self.passwd)

    def _format_addr(self, s):
        addr = parseaddr(s)
        return formataddr(addr)



    def send(self, msg_to, details):
        # print(name,orderNo,fileUrl,msg_to)
        title = "小马托运-{}".format(details.get('order_no', ''))
       
        # 默认详情字段
        default = {
            "order_no":'',
            "start_city": "-",
            "end_city": "-",
            "sender": "-",
            "sender_phone": "-",
            "receiver": "-",
            "receiver_phone": "-",
            "quoted_price": "-",
            "insurance_fee": "-",
            "pickup_time": "-",
            "package_type": "-",
            "delivery_type": "-",
        }
        if details:
            default.update(details)
        d = default
        
        html = f"""
        <!DOCTYPE html>
        <html lang='zh-CN'>
        <head>
            <meta charset='utf-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1,maximum-scale=1'>
            <style>
                body{{font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; margin:0;padding:16px;color:#333;}}
                .container{{max-width:600px;margin:0 auto;background:#fff;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.05);padding:20px;}}
                h2{{font-size:18px;margin:0 0 12px 0;color:#1890ff;}}
                table{{width:100%;border-collapse:collapse;font-size:14px;}}
                th,td{{padding:8px 6px;text-align:left;border-bottom:1px solid #f0f0f0;}}
                th{{background:#fafafa;width:40%;color:#555;}}
                @media (max-width:480px){{
                    th,td{{display:block;width:100%;box-sizing:border-box;}}
                    th{{background:none;font-weight:bold;border:none;padding-top:12px;}}
                    td{{border:none;padding-bottom:12px;}}
                }}
            </style>
        </head>
        <body>
            <div class='container'>
                <h2>小马托运 - 订单 {d.get('order_no', '')} 已支付</h2>
                <p style='line-height:1.7em;'>您好，订单已支付成功，详情如下：</p>
                <table>
                    <tr><th>起始地</th><td>{d['start_city']}</td></tr>
                    <tr><th>目的地</th><td>{d['end_city']}</td></tr>
                    <tr><th>货物类型</th><td>{d['goods_type']}</td></tr>
                    <tr><th>发货人</th><td>{d['sender']}（{d['sender_phone']}）</td></tr>
                    <tr><th>收货人</th><td>{d['receiver']}（{d['receiver_phone']}）</td></tr>
                    <tr><th>已报价</th><td>{d['quoted_price']}</td></tr>
                    <tr><th>保价费</th><td>{d['insurance_fee']}</td></tr>
                    <tr><th>预计上门时间</th><td>{d['pickup_time']}</td></tr>
                    <tr><th>包装类型</th><td>{d['package_type']}</td></tr>
                    <tr><th>发货类型</th><td>{d['delivery_type']}</td></tr>
                    <tr><th>订单总金额</th><td>{d['total_price']}</td></tr>
                    <tr><th>实际付款金额</th><td>{d['pay_price']}</td></tr>
                    <tr><th>用户手机号</th><td>{d['user_phone']}</td></tr>
                </table>
                <p style='margin-top:16px;font-size:12px;color:#888;'>如有疑问，请与客服联系。</p>
            </div>
        </body>
        </html>
        """
        content = MIMEText(html, 'html', 'utf-8')  # 正文

        msg = MIMEMultipart('related')
        msg.attach(content)
        msg['Subject'] = title
        # msg['From'] = "THUAC色谱与分离实验室"
        msg['From'] = self.msg_from

        msg['to'] = msg_to

        msg_to_list = [msg_to]
        try:
            self.s.sendmail(self.msg_from, msg_to_list,
                            msg.as_string().encode('utf-8'))
            self.s.quit()
            # print("发送成功")
        except Exception as e:
            print(e)
            print("发送失败")


if __name__ == '__main__':

    params = sys.argv
    if len(params) < 3:
        print("用法: python em.py <email> <details_json>")
        sys.exit(1)
    
    msg_to = params[1]
    details_str = ' '.join(params[2:])
    try:
        details = json.loads(details_str)
    except ValueError:
        try:
            details = ast.literal_eval(details_str)
        except Exception as e:
            print("详情解析失败:", e)
            sys.exit(1)
    m = EM()
    m.send(msg_to, details)


    # msg_to = '854013212@qq.com'
    # m.send(msg_to, {
    #     "start_city": "北京",
    #     "end_city": "上海",
    #     "sender": "张三",
    #     "sender_phone": "138****0000",
    #     "receiver": "李四",
    #     "receiver_phone": "139****1111",
    #     "quoted_price": "¥300",
    #     "insurance_fee": "¥20",
    #     "pickup_time": "2023-09-23 14:00",
    #     "package_type": "纸箱",
    #     "delivery_type": "门到门",
    #     "order_no": "123123123",
    # })

    # m = EM()
    # m.send( '2023022706350284','854013212@qq.com')
